"""
Copyright 2007 VMware, Inc.  All rights reserved. -- VMware Confidential

@todo: We should log more informative messages (like line number,
etc.) for errors and above.
"""

import os
import pwd
import logging

from logging.handlers import RotatingFileHandler

import vmis

level = os.environ.get('VMIS_LOG_LEVEL') or getattr(vmis, 'LOG_LEVEL', 'INFO')
level = getattr(logging, level)

if os.getuid() == 0:
   LOG_FILE = '/var/log/vmware-installer'
else:
   # Log to a user-writable location since we're not root (like when
   # running a build)
   username = pwd.getpwuid(os.getuid())[0]
   dirname = '/tmp/vmware-%s' % username
   LOG_FILE = '%s/vmware-installer.log' % dirname
   # Make sure this directory exists.  Assuming /tmp exists.
   try:
      os.mkdir(dirname)
   except OSError:
      # It's okay if it already exists
      pass

if level <= logging.DEBUG:
   MAX_BYTES = 0
   BACKUP_COUNT = 0
else:
   MAX_BYTES = 2 ** 20 # 1 MB
   BACKUP_COUNT=1

def setLevel(level):
   """
   Set the global log level.

   @param level: one of the log levels from L{logging}
   """
   fileLogger.setLevel(level)

def getLog(name):
   """
   Returns the logger with the given name.

   @param name: dot-separated name of the logger
   """
   return logging.getLogger(name)

def Shutdown():
   """ Shutdown logging """
   logging.shutdown()

getLog(None).setLevel(level)

fileLogger = RotatingFileHandler(LOG_FILE, maxBytes=MAX_BYTES, backupCount=BACKUP_COUNT)
#fileLogger.setFormatter(logging.Formatter('%(name)s %(module)s.%(funcName)s %(lineno)d %(message)s'))
fileLogger.setFormatter(logging.Formatter(u'[%(asctime)s] %(message)s'))
getLog(None).addHandler(fileLogger)
